<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java学习,">










<meta name="description" content="摘要：多线程">
<meta name="keywords" content="Java学习">
<meta property="og:type" content="article">
<meta property="og:title" content="Java之多线程，线程安全，线程池">
<meta property="og:url" content="/youbaaa.github.io/2018/06/11/Java之多线程，线程安全，线程池/index.html">
<meta property="og:site_name" content="vlsion&#39;手记">
<meta property="og:description" content="摘要：多线程">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-08-07T00:19:01.649Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java之多线程，线程安全，线程池">
<meta name="twitter:description" content="摘要：多线程">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="/youbaaa.github.io/2018/06/11/Java之多线程，线程安全，线程池/">





  <title>Java之多线程，线程安全，线程池 | vlsion'手记</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">vlsion'手记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">擅长Ai、Fw、Fl、Br、Ae、Pr、Id、PS等软件的安装与卸载，精通CSS、JavaScript、PHP、C、C＋＋、java、Ruby、Perl、Lisp、python、Objective-C、ActionScript等单词的拼写，熟悉windows、Linux、Mac、Android、IOS等系统的开关机</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="/youbaaa.github.io/2018/06/11/Java之多线程，线程安全，线程池/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="vlsion_">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/uploads/girl.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vlsion'手记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java之多线程，线程安全，线程池</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-11T11:23:02+08:00">
                2018-06-11
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java中级/" itemprop="url" rel="index">
                    <span itemprop="name">Java中级</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/06/11/Java之多线程，线程安全，线程池/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/06/11/Java之多线程，线程安全，线程池/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/06/11/Java之多线程，线程安全，线程池/" class="leancloud_visitors" data-flag-title="Java之多线程，线程安全，线程池">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>摘要：多线程<br> <a id="more"></a><br>名词解释：<br>进程：进程是指一个系统上运行的一个应用程序，一个应用程序可以有多个进程。进程也是程序的一次执行过程，是系统运行程序的基本单位；系统运行一个程序即是一个进程从创 建、运行到消亡的过程。<br>线程：线程是进程中最小的执行单元，一个进程最少有一个线程，一个进程可以有多个线程（即为多线程程序）<br>并发：指俩个或多个事件在同一时间段发生。<br>并行：指俩个或多个事件在同一时刻发生。</p>
<h3 id="线程创建"><a href="#线程创建" class="headerlink" title="线程创建"></a>线程创建</h3><h4 id="Java中线程的创建方式一：继承Thread类，重写run-方法；"><a href="#Java中线程的创建方式一：继承Thread类，重写run-方法；" class="headerlink" title="Java中线程的创建方式一：继承Thread类，重写run()方法；"></a>Java中线程的创建方式一：继承Thread类，重写run()方法；</h4><p>构造方法：<br>public Thread() :分配一个新的线程对象。<br>public Thread(String name) :分配一个指定名字的新的线程对象。<br>public Thread(Runnable target) :分配一个带有指定目标新的线程对象。<br>public Thread(Runnable target,String name) :分配一个带有指定目标新的线程对象并指定名字。<br>常用方法：<br>public String getName() :获取当前线程名称。<br>public void start() :导致此线程开始执行; Java虚拟机调用此线程的run方法。<br>public void run() :此线程要执行的任务在此处定义代码。<br>public static void sleep(long millis) :使当前正在执行的线程以指定的毫秒数暂停（暂时停止执行）。<br>public static Thread currentThread() :返回对当前正在执行的线程对象的引用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public class MyThread extends Thread&#123;</span><br><span class="line">    /*</span><br><span class="line">    *利用继承中的特点</span><br><span class="line">    *将线程名称传递 进行设置</span><br><span class="line">    */</span><br><span class="line">    public MyThread(String name)&#123; </span><br><span class="line">        super(name);</span><br><span class="line">    &#125;</span><br><span class="line">    /*</span><br><span class="line">    *重写run方法</span><br><span class="line">    *定义线程要执行的代码</span><br><span class="line">    */</span><br><span class="line">    public void run()&#123;</span><br><span class="line">        for (int i = 0; i &lt; 20; i++) &#123;</span><br><span class="line">            //getName()方法 来自父亲</span><br><span class="line">            System.out.println(getName()+i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public class Demo &#123;</span><br><span class="line">    public static void main(String[] args) &#123; </span><br><span class="line">        System.out.println(&quot;这里是main线程&quot;);</span><br><span class="line">         MyThread mt = new MyThread(&quot;小强&quot;);</span><br><span class="line">         mt.start();//开启了一个新的线程</span><br><span class="line">         for (int i = 0; i &lt; 20; i++) &#123; </span><br><span class="line">            System.out.println(&quot;旺财:&quot;+i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="Java中线程的创建方式二：实现Runable接口，重写run-方法；"><a href="#Java中线程的创建方式二：实现Runable接口，重写run-方法；" class="headerlink" title="Java中线程的创建方式二：实现Runable接口，重写run()方法；"></a>Java中线程的创建方式二：实现Runable接口，重写run()方法；</h4><p>通过实现Runable接口，使该类具有多线程类特征。run()方法是多线程的一个执行目标，所有的多线程代码都在run()方法体类。Thread类也是实现了Ruable接口的类。<br>tips:Runnable对象仅仅作为Thread对象的target，Runnable实现类里包含的run()方法仅作为线程执行体。而实际的线程对象依然是Thread实例，只是该Thread线程负责执行其target的run()方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class MyRunnable implements Runnable&#123; </span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        for (int i = 0; i &lt; 20; i++) &#123; </span><br><span class="line">            System.out.println(Thread.currentThread().getName()+&quot; &quot;+i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>测试类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public class Demo &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        //创建自定义类对象 线程任务对象</span><br><span class="line">        MyRunnable mr = new MyRunnable();</span><br><span class="line">        //创建线程对象</span><br><span class="line">        Thread t = new Thread(mr, &quot;小强&quot;);</span><br><span class="line">        t.start();</span><br><span class="line">        for (int i = 0; i &lt; 20; i++) &#123;</span><br><span class="line">             System.out.println(&quot;旺财 &quot; + i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>推荐使用方式二创建线程，原因如下：<br>1，实现Runable接口，解决了java中类单继承的局限性。<br>2，增加了程序的健壮性，实现了解藕操作，实现了代码共享，代码和线程独立。<br>3，线程池只能放入实现Runable接口或者Callable接口的类，不能放入继承Thread类的类。</p>
<p>tips：使用匿名内部类方式创建线程：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public class NoNameInnerClassThread &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">    //	new Runnable()&#123;</span><br><span class="line">    //	public void run()&#123;</span><br><span class="line">    //	for (int i = 0; i &lt; 20; i++) &#123;</span><br><span class="line">    //	System.out.println(&quot;张宇:&quot;+i);</span><br><span class="line">    //	&#125;</span><br><span class="line">    //	&#125;</span><br><span class="line">    //	&#125;; //‐‐‐这个整体 相当于new MyRunnable()</span><br><span class="line">        Runnable r = new Runnable()&#123;</span><br><span class="line">            public void run()&#123;</span><br><span class="line">                for (int i = 0; i &lt; 20; i++) &#123; </span><br><span class="line">                    System.out.println(&quot;张宇:&quot;+i);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        new Thread(r).start();</span><br><span class="line">        for (int i = 0; i &lt; 20; i++) &#123;</span><br><span class="line">            System.out.println(&quot;费玉清:&quot;+i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="线程同步（线程安全）"><a href="#线程同步（线程安全）" class="headerlink" title="线程同步（线程安全）"></a>线程同步（线程安全）</h3><p>1，同步代码块：synchronized 关键字用于方法中某个代码块，表示只对方法中找个区块中的类容进行互斥作用。格式：<br>synchronized(同步锁){<br>    同步代码块<br>}</p>
<p>比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">public class Ticket implements Runnable &#123;</span><br><span class="line">    private int ticket = 100;</span><br><span class="line">    Object lock = new Object();</span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        //每个窗口卖票的操作</span><br><span class="line">        //窗口 永远开启</span><br><span class="line">        while (true) &#123;</span><br><span class="line">            synchronized (lock)&#123;</span><br><span class="line">                if (ticket &gt; 0) &#123;//有票 可以卖</span><br><span class="line">                    //出票操作</span><br><span class="line">                    //使用sleep模拟一下出票时间</span><br><span class="line">                    try &#123;</span><br><span class="line">                        Thread.sleep(100);</span><br><span class="line">                    &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                    // TODO Auto‐generated catch block</span><br><span class="line">                         e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                    //获取当前线程对象的名字</span><br><span class="line">                    String name = Thread.currentThread().getName();</span><br><span class="line">                    System.out.println(name + &quot;正在卖:&quot; + ticket--);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2，同步方法：synchronized 修饰的方法叫做同步方法，保证当该方法被某线程执行时，其他线程执行它时只能等着。格式：<br>public synchronized void method(){<br>    代码<br>}</p>
<p>比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">public class Ticket implements Runnable &#123;</span><br><span class="line">    Object lock = new Object();</span><br><span class="line">    private int ticket = 100;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        //每个窗口卖票的操作</span><br><span class="line">        //窗口 永远开启</span><br><span class="line">        while (true) &#123;</span><br><span class="line">            sellTicket();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public synchronized void sellTicket() &#123;</span><br><span class="line">        if (ticket &gt; 0) &#123;//有票 可以卖</span><br><span class="line">            //出票操作</span><br><span class="line">            //使用sleep模拟一下出票时间</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(100);</span><br><span class="line">            &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                // TODO Auto‐generated catch block e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            //获取当前线程对象的名字</span><br><span class="line">            String name = Thread.currentThread().getName();</span><br><span class="line">            System.out.println(name + &quot;正在卖:&quot; + ticket--);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3， Lock锁： java.util.concurrent.locks.Lock 机制提供了比synchronized代码块和synchronized方法更广泛的锁定操作, 同步代码块/同步方法具有的功能Lock都有,除此之外更强大,更体现面向对象。<br>Lock锁也称同步锁，加锁与释放锁方法化了，如下：<br>public void lock() :加同步锁。<br>public void unlock() :释放同步锁。</p>
<p>比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public class Ticket implements Runnable &#123;</span><br><span class="line">    Lock lock = new ReentrantLock();</span><br><span class="line">    private int ticket = 100;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        //每个窗口卖票的操作</span><br><span class="line">        //窗口 永远开启</span><br><span class="line">        while (true) &#123;</span><br><span class="line">            lock.lock();</span><br><span class="line">            if (ticket &gt; 0) &#123;//有票 可以卖</span><br><span class="line">                //出票操作</span><br><span class="line">                //使用sleep模拟一下出票时间</span><br><span class="line">                try &#123;</span><br><span class="line">                    Thread.sleep(100);</span><br><span class="line">                &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                    // TODO Auto‐generated catch block e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                //获取当前线程对象的名字</span><br><span class="line">                String name = Thread.currentThread().getName();</span><br><span class="line">                System.out.println(name + &quot;正在卖:&quot; + ticket--);</span><br><span class="line">            &#125;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h3><p>合理的使用线程池的好处：<br>1，降低系统资源的消耗。减少线程创建和销毁所占用的资源消耗。<br>2，提高响应速度。复用创建过的线程，减少线程创建销毁所需时间。<br>3，提高线程的客观理性。线程是稀缺资源，如果无限制地创建，不仅会消耗系统资源，<br>还会降低系统的稳定性，使用线程池可以进行统一分配、调优和监控。</p>
<p>线程池时为突然爆发大量线程设计的，它可以减少线程创建销毁的时间，提高运行效率。如果一个线程过长就没必要用线程池了（不是不能，是不适合），线程池中的线程，我们无法进行开始挂起中止操作。</p>
<p>线程池的分类：<br>Executor接口是在JDK1.5（2004）年时引入的java.util.concurrent包中。<br>Executor框架最顶层的实现是ThreadPoolExcutor类，Excutor工厂类提供的newScheduledThreadPool、newFixedThreadPool、newCachedThreadPool方法其实也只是ThreadPoolExecutor的构造函数参数不同而已。通过传入不同的参数，就可以构造出适用于不同应用场景下的线程池。<br>corePoolSize： 核心池的大小。 当有任务来之后，就会创建一个线程去执行任务，当线程池中的线程数目达到corePoolSize后，就会把到达的任务放到缓存队列当中<br>maximumPoolSize： 线程池最大线程数，它表示在线程池中最多能创建多少个线程；<br>keepAliveTime： 表示线程没有任务执行时最多保持多久时间会终止。<br>unit： 参数keepAliveTime的时间单位，有7种取值，在TimeUnit类中有7种静态属性。</p>
<p>线程池的创建方式：<br>Excutor提供四种线程池：</p>
<p>newCachedThreadPool创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。</p>
<p>newFixedthreadPool创建一个定长线程池，可以控制线程最大的并发数，超出的线程会在队列中等待。</p>
<p>newScheduledThreadPool创建一个定长线程池，支持定时及周期性任务执行。</p>
<p>newSingleThreadExecutor 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。</p>
<p>newCachedThreadPool<br>创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲的线程，若无可回收，则新建线程。总结: 线程池为无限大，当执行第二个任务时第一个任务已经完成，会复用执行第一个任务的线程，而不用每次新建线程。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public class Demo &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        ExecutorService executorService = Executors.newCachedThreadPool();</span><br><span class="line">        for (int i = 0; i &lt; 10; i++) &#123;</span><br><span class="line">            final int temp = i;</span><br><span class="line">            executorService.execute(new Runnable() &#123;</span><br><span class="line">                @Override</span><br><span class="line">                public void run() &#123;</span><br><span class="line">                    try &#123;</span><br><span class="line">                        Thread.sleep(100);</span><br><span class="line">                    &#125; catch (Exception e) &#123;</span><br><span class="line">                        // TODO: handle exception</span><br><span class="line">                    &#125;</span><br><span class="line">                    System.out.println(Thread.currentThread().getName() + &quot;,i:&quot; + temp);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>newFixedThreadPool<br>创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。<br>总结:因为线程池大小为3，每个任务输出index后sleep 2秒，所以每两秒打印3个数字。<br>定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">ExecutorService executorService = Executors.newFixedThreadPool(3);</span><br><span class="line">for (int i = 0; i &lt; 10; i++) &#123;</span><br><span class="line">    final int temp = i;</span><br><span class="line">    executorService.execute(new Runnable() &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(100);</span><br><span class="line">            &#125; catch (Exception e) &#123;</span><br><span class="line">                // TODO: handle exception</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + &quot;,i:&quot; + temp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>newScheduledThreadPool<br>创建一个定长线程池，支持定时及周期性任务执行。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">ExecutorService executorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());</span><br><span class="line">for (int i = 0; i &lt; 10; i++) &#123;</span><br><span class="line">    final int temp = i;</span><br><span class="line">    ((ScheduledExecutorService) executorService).schedule(new Runnable() &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(1000);</span><br><span class="line">            &#125; catch (Exception e) &#123;</span><br><span class="line">                // TODO: handle exception</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + &quot;,i:&quot; + temp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,10, TimeUnit.SECONDS);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>newSingleThreadExecutor<br>创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">ExecutorService executorService = Executors.newSingleThreadExecutor();</span><br><span class="line">for (int i = 0; i &lt; 10; i++) &#123;</span><br><span class="line">    final int temp = i;</span><br><span class="line">    (executorService).execute(new Runnable() &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(1000);</span><br><span class="line">            &#125; catch (Exception e) &#123;</span><br><span class="line">                // TODO: handle exception</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + &quot;,i:&quot; + temp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="合理配置线程池"><a href="#合理配置线程池" class="headerlink" title="合理配置线程池"></a>合理配置线程池</h3><p>CPU密集<br>CPU密集的意思是该任务需要大量的运算，而没有阻塞，CPU一直全速运行。<br>CPU密集任务只有在真正的多核CPU上才可能得到加速(通过多线程)，而在单核CPU上，无论你开几个模拟的多线程，该任务都不可能得到加速，因为CPU总的运算能力就那些。<br>IO密集<br>IO密集型，即该任务需要大量的IO，即大量的阻塞。在单线程上运行IO密集型的任务会导致浪费大量的CPU运算能力浪费在等待。所以在IO密集型任务中使用多线程可以大大的加速程序运行，即时在单核CPU上，这种加速主要就是利用了被浪费掉的阻塞时间。<br>接着上一篇探讨线程池留下的尾巴，如何合理的设置线程池大小。<br>要想合理的配置线程池的大小，首先得分析任务的特性，可以从以下几个角度分析：<br>任务的性质：CPU密集型任务、IO密集型任务、混合型任务。<br>任务的优先级：高、中、低。<br>任务的执行时间：长、中、短。<br>任务的依赖性：是否依赖其他系统资源，如数据库连接等。<br>性质不同的任务可以交给不同规模的线程池执行。<br>对于不同性质的任务来说，CPU密集型任务应配置尽可能小的线程，如配置CPU个数+1的线程数，IO密集型任务应配置尽可能多的线程，因为IO操作不占用CPU，不要让CPU闲下来，应加大线程数量，如配置两倍CPU个数+1，而对于混合型的任务，如果可以拆分，拆分成IO密集型和CPU密集型分别处理，前提是两者运行的时间是差不多的，如果处理时间相差很大，则没必要拆分了。<br>若任务对其他系统资源有依赖，如某个任务依赖数据库的连接返回的结果，这时候等待的时间越长，则CPU空闲的时间越长，那么线程数量应设置得越大，才能更好的利用CPU。<br>当然具体合理线程池值大小，需要结合系统实际情况，在大量的尝试下比较才能得出，以上只是前人总结的规律。<br>最佳线程数目 = （（线程等待时间+线程CPU时间）/线程CPU时间 ）* CPU数目<br>比如平均每个线程CPU运行时间为0.5s，而线程等待时间（非CPU运行时间，比如IO）为1.5s，CPU核心数为8，那么根据上面这个公式估算得到：((0.5+1.5)/0.5)8=32。<br>这个公式进一步转化为：最佳线程数目 = （线程等待时间与线程CPU时间之比 + 1） CPU数目<br>可以得出一个结论：<br>线程等待时间所占比例越高，需要越多线程。线程CPU时间所占比例越高，需要越少线程。<br>以上公式与之前的CPU和IO密集型任务设置线程数基本吻合。<br>CPU密集型时，任务可以少配置线程数，大概和机器的cpu核数相当，这样可以使得每个线程都在执行任务<br>IO密集型时，大部分线程都阻塞，故需要多配置线程数，2*cpu核数<br>操作系统之名称解释：<br>某些进程花费了绝大多数时间在计算上，而其他则在等待I/O上花费了大多是时间，<br>前者称为计算密集型（CPU密集型）computer-bound，后者称为I/O密集型，I/O-bound。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java学习/" rel="tag"># Java学习</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/20/Tomcat上线服务器参数调整/" rel="next" title="性能优化之上线服务器参数调整">
                <i class="fa fa-chevron-left"></i> 性能优化之上线服务器参数调整
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/15/Java之IO流/" rel="prev" title="Java之IO流">
                Java之IO流 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/girl.jpg" alt="vlsion_">
            
              <p class="site-author-name" itemprop="name">vlsion_</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#线程创建"><span class="nav-number">1.</span> <span class="nav-text">线程创建</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Java中线程的创建方式一：继承Thread类，重写run-方法；"><span class="nav-number">1.1.</span> <span class="nav-text">Java中线程的创建方式一：继承Thread类，重写run()方法；</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Java中线程的创建方式二：实现Runable接口，重写run-方法；"><span class="nav-number">1.2.</span> <span class="nav-text">Java中线程的创建方式二：实现Runable接口，重写run()方法；</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程同步（线程安全）"><span class="nav-number">2.</span> <span class="nav-text">线程同步（线程安全）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程池"><span class="nav-number">3.</span> <span class="nav-text">线程池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#合理配置线程池"><span class="nav-number">4.</span> <span class="nav-text">合理配置线程池</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vlsion_</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '9mmqXgbwBLayRV0R9zW2iCxe-gzGzoHsz',
        appKey: 'U0JFc0fpsnrOvTdgoBKRSXwz',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
